package com.aks.student.career.dao;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * User: tr1a6333
 * Date: 22.07.2011
 * Time: 14:18
 */
public abstract class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID>, Serializable {


    private Class<T> persistentClass;

    @Autowired
    protected SessionFactory sessionFactory;

    protected HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        return new HibernateTemplate(sessionFactory);
    }

    @SuppressWarnings("unchecked")
    public GenericDAOImpl() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public T loadById(ID id) {
        return (T) sessionFactory.getCurrentSession().load(persistentClass, id);
    }

    public ID save(T obj) {
        Object o = sessionFactory.getCurrentSession().save(obj);
        return (ID) o;
    }


    public void update(T obj) {

        sessionFactory.getCurrentSession().saveOrUpdate(obj);

    }

    public void delete(T obj) {
        sessionFactory.getCurrentSession().delete(obj);
    }

    public List<T> findAll(Class persistanceClass) {
        Session session = sessionFactory.getCurrentSession();
        Criteria cr = session.createCriteria(persistanceClass);
        cr.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        return cr.list();
    }

    public T findById(Class persistanceClass, ID id) {
        Session session = sessionFactory.getCurrentSession();
        Criteria cr = session.createCriteria(persistanceClass).add(Restrictions.eq("id", id));
        List temp = cr.list();
        if (temp.size() > 0)
            return (T) temp.get(0);
        else
            return null;
    }


}//GenericDAOImpl



